<template>
  <div> 
    <el-dialog v-model="dialogVisible" title="颜色选择器" width="500" draggable :fullscreen="false" :show-close="false">
      <div> 
        <div id="colorBox" class="color-box"  @click="pickColor">
          选择颜色
        </div> 
      </div>

      <div class="color-buttons">
        <el-button
          v-for="(color, index) in colorList"
          :key="index"
          :style="{ backgroundColor: color,width:'100px' }"
          @click="copyColor(color)"
        >
          {{ color }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

// 控制弹窗显示状态
const dialogVisible = ref(true);

// 从 localStorage 中读取颜色值
const colorList = ref(JSON.parse(localStorage.getItem('colorList')) || []);

// 取色逻辑
const pickColor = async () => {
  const eyeDropper = new EyeDropper();
  try {
    const { sRGBHex } = await eyeDropper.open();
    const colorBox = document.getElementById('colorBox');
    colorBox.style.backgroundColor = sRGBHex;
    colorBox.textContent = `颜色值: ${sRGBHex}`;

    // 复制颜色值到剪贴板
    navigator.clipboard.writeText(sRGBHex);

    // 保存颜色值到 localStorage
    colorList.value.push(sRGBHex);
    localStorage.setItem('colorList', JSON.stringify(colorList.value));

    // 使用 Element Plus 的 ElMessage 显示提示
    ElMessage.success(`颜色值 ${sRGBHex} 已复制到剪贴板`);
  } catch (error) {
    console.error('取色操作已取消或发生错误', error);
    ElMessage.error('取色操作已取消或发生错误');
  }
};

// 复制颜色值到剪贴板
const copyColor = (color) => {
  navigator.clipboard.writeText(color);
  ElMessage.success(`颜色值 ${color} 已复制到剪贴板`);
};
</script>

<style scoped>
.color-box {
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.color-buttons {
  margin-top: 20px;
}

.color-buttons .el-button {
  margin: 5px;
  color: white;
  font-size: 12px;
}
</style>